﻿/**
 * SlotDuino
 * 
 * Copyright (c) 2011/2012 Thiago Hummel Moreira, Ricardo Mizuuti, Rafael Mufato, Bruno Sakai, Andre Turina
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
using System;
using System.Data;
using System.Windows.Controls;
using System.Windows.Data;
using SlotDuino.DAL;
using System.Windows;
using System.Linq;
using System.Collections.ObjectModel;
using SlotDuino.Util;


namespace SlotDuino.UI.Pages
{
    /// <summary>
    /// Interaction logic for TrackConfig.xaml
    /// </summary>
    public partial class TrackConfig : Page
    {
        #region Dependency properties
        public static readonly DependencyProperty TrackProperty = DependencyProperty.Register("Track", typeof(Track), typeof(TrackConfig));
        #endregion

        #region Private attributes
        private EntityContainer _context;
        #endregion

        #region Public properties
        public Track Track
        {
            get { return (Track)GetValue(TrackProperty); }
            set { SetValue(TrackProperty, value); }
        }
        #endregion

        #region Constructors
        public TrackConfig()
        {
            InitializeComponent();
        }
        #endregion

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            _context = new EntityContainer();
            
            Track = ((App)Application.Current).GetCurrentTrack(_context);
            
            if (Track.HasVoltageControl)
            {
                cmbVoltage.SelectedIndex = Track.Voltages.Count() / 2;
            }

            cmbNumSlots.SelectedIndex = Track.Slots.Count() - 1;
        }

        private void cmbVoltage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (null == Track) return;

            int voltageCount = cmbVoltage.SelectedIndex * 2,
                lastId = Track.Voltages.Count,
                delta = lastId - voltageCount;

            //Add 
            if (delta < 0)
            {
                delta = Math.Abs(delta);

                for (int i = 1; i <= delta; i++)
                {
                    Voltage voltage = new Voltage();
                    voltage.Id = (byte)(lastId + i);
                    voltage.Label = "N/D";
                    Track.Voltages.Add(voltage);
                }

            }
            //Remove
            else if (delta > 0)
            {
                for (int i = 1; i <= delta; i++)
                {
                    var instance = Track.Voltages.ElementAt(lastId - i);
                    Track.Voltages.Remove(instance);
                }
            }
            
            Track.HasVoltageControl = (voltageCount > 0);
        }

        private void cmbNumLanes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (null == Track) return;

            int slotsCount = cmbNumSlots.SelectedIndex +1,
                lastId = Track.Slots.Count,
                delta = lastId - slotsCount;

            //Add 
            if (delta < 0)
            {
                delta = Math.Abs(delta);

                for (int i = 1; i <= delta; i++)
                {
                    Slot slot = new Slot();
                    slot.Id = (byte)(lastId + i);
                    slot.Color = "N/D";
                    Track.Slots.Add(slot);
                }

            }

            //Remove
            else if (delta > 0)
            {
                for (int i = 1; i <= delta; i++)
                {
                    var instance = Track.Slots.ElementAt(lastId - i);
                    Track.Slots.Remove(instance);
                }
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //Save changes to DB
                _context.SaveChanges();
                
                //Save changes to SlotDaemon
                ((App)Application.Current).Client.SetConfig(Track);

                Msg.ShowOk(String.Format("Configurações da '{0}' atualizada com sucesso !", Track.Name));
                
                //Go back to dashboard
                NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                Msg.ShowError(ex.Message);
            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }
    }
}
